package com.unohacha.qqj.fzdr.main;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppFzSchoolBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeBannerBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeFzSchoolBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.personal.view.activity.FzDetailActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.ShowPdfActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.WebViewHomeActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.MyRecyclerView;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 纺织学堂 item_fz_school
 */
public class FzSchoolActivity extends BaseActivity implements OnRefreshLoadmoreListener {


    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.pt_tabs)
    TabLayout mTabLayout;
    @BindView(R.id.pt_line)
    ImageView ptLine;
    @BindView(R.id.car_list_recycler)
    MyRecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.title_ll)
    LinearLayout titleLl;
    @BindView(R.id.common_cancle)
    ImageView commonCancle;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.common_right_search)
    TextView commonRightSearch;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.banner)
    Banner banner;

    private List<String> mFragmentsTitle = new ArrayList<String>();//碎片的标题
    private List<HomeAppFzSchoolBean.DataBean> mCateList = new ArrayList<>();
    private List<HomeFzSchoolBean.DataBeanX.DataBean> mFzSchoolList = new ArrayList<>();
    private List<HomeBannerBean.DataBean> mBannerAllList = new ArrayList<>();//banner的集合
    private List<String> mBannerList = new ArrayList<>();
    private int page = 1;
    private BaseRVAdapter mBaseAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_fz_school;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.fz_school));
        commonRightText.setVisibility(View.GONE);
        commonRightImage.setVisibility(View.VISIBLE);
        commonRightImage.setImageResource(R.drawable.ic_search_black);

        initRefreshLayout();
        getAppCateList();
        getBannerData(34);
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        carListRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }

    //初始化tab
    private void initTabLayout(List<String> mFragmentsTitle0) {

        if (null != mFragmentsTitle0 && null != mCateList) {
            for (int i = 0; i < mFragmentsTitle0.size(); i++) {
                mTabLayout.addTab(mTabLayout.newTab().setText(mFragmentsTitle.get(i)), i);
            }
            getAppFzSchoolData(mCateList.get(0).getId(), "");
            System.out.println("mCateList.get(0).getId()=" + mCateList.get(0).getId());
            mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.black));
            mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
            mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    page = 1;
                    getAppFzSchoolData(mCateList.get(tab.getPosition()).getId(), "");
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {
                }
            });
        }
    }

    //获取banner 集合数据
    private void getBannerData(int typeid) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("typeid", typeid);//4-面料供求 5-制造供求 6-原料供求 7-辅料供应 8-人才招聘 29-求职发布
        XUtil.Post(UrlConfig.AD_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeBannerBean bannerBean = gson.fromJson(result, HomeBannerBean.class);
                        if (null != bannerBean) {
                            if (null != mBannerAllList) {
                                mBannerAllList.clear();
                            }
                            mBannerAllList.addAll(bannerBean.getData());
                            setBannerData();
                        }
                        mRefreshLayout.finishLoadmore();
                        mRefreshLayout.finishLoadmoreWithNoMoreData();
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置banner 数据
    private void setBannerData() {
        if (null != mBannerAllList) {
            for (int i = 0; i < mBannerAllList.size(); i++) {
                mBannerList.add(i, mBannerAllList.get(i).getImg_face());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置圆形指示器与标题
            banner.setIndicatorGravity(BannerConfig.CENTER);//设置指示器位置
            banner.setImages(mBannerList);
            banner.setImageLoader(new GlideImageLoader());
            banner.start();

            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    //用mBannerAllList集合
                }
            });
        }
    }


    //获取纺织学堂的分类标题
    private void getAppCateList() {
        Map<String, Object> params = new HashMap<>();
        params.put("id", 50);
        XUtil.Post(UrlConfig.APP_CATE_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppFzSchoolBean schoolBean = gson.fromJson(result, HomeAppFzSchoolBean.class);
                        if (null != schoolBean) {
                            if (null != mCateList) {
                                mCateList.clear();
                            }
                            mCateList.addAll(schoolBean.getData());
                            for (int i = 0; i < mCateList.size(); i++) {
                                mFragmentsTitle.add(i, mCateList.get(i).getName());
                            }
                            initTabLayout(mFragmentsTitle);
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //获取纺织学堂的列表数据
    private void getAppFzSchoolData(int app_cate_id, String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("app_cate_id", app_cate_id);
        params.put("keyword", keyword);
        params.put("page", page);
        XUtil.Post(UrlConfig.APP_FX_SCHOOL_INFO, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {

                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeFzSchoolBean fzSchoolBean = gson.fromJson(result, HomeFzSchoolBean.class);
                        if (null != fzSchoolBean) {
                            if (page == 1) {
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                if (null != mFzSchoolList) {
                                    mFzSchoolList.clear();
                                }
                                mFzSchoolList.addAll(fzSchoolBean.getData().getData());
                            } else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                            setmFzSchoolAdapter();
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        if (page == 1) {
                            MyToast(jsonObject.optString("message"));
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            if (null != mFzSchoolList) {
                                mFzSchoolList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                        } else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置纺织学堂的数据
    private void setmFzSchoolAdapter() {
        mBaseAdapter = new BaseRVAdapter(this, mFzSchoolList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_fz_school;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                if (null != mFzSchoolList) {
                    ImageView iv_fz_school = holder.getImageView(R.id.iv_fz_school);
                    TextView title_fz_school = holder.getTextView(R.id.title_fz_school);
                    TextView content_fz_school = holder.getTextView(R.id.content_fz_school);
                    TextView time_fz_school = holder.getTextView(R.id.time_fz_school);
                    TextView comment_num = holder.getTextView(R.id.comment_num);
                    if (!TextUtils.isEmpty(mFzSchoolList.get(position).getThumb())) {
                        Glide.with(FzSchoolActivity.this).load(mFzSchoolList.get(position).getThumb())
                                .into(iv_fz_school);
                    } else {
                        iv_fz_school.setBackgroundColor(getResources().getColor(R.color.bg_gray));
                    }
                    title_fz_school.setText(mFzSchoolList.get(position).getTitle());
                    content_fz_school.setText(mFzSchoolList.get(position).getIntroduction());
                    time_fz_school.setText(mFzSchoolList.get(position).getCreate_time());
                    comment_num.setText(mFzSchoolList.get(position).getCommon_nums() + "评");
                }
            }
        };
        carListRecycler.setAdapter(mBaseAdapter);
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
//                ToastUtils.showT(mFzSchoolList.get(position).getId() + "");
                final int a = mFzSchoolList.get(position).getStatus();
                switch (a) {
                    case 1:
                        Intent intent = new Intent(FzSchoolActivity.this, FzDetailActivity.class);
                        intent.putExtra("id", mFzSchoolList.get(position).getId() + "");
                        startActivity(intent);
                        break;
                    case 2:
                        Intent intent2 = new Intent(FzSchoolActivity.this, ShowPdfActivity.class);
                        intent2.putExtra("url", mFzSchoolList.get(position).getUrl() + "");
                        intent2.putExtra("title", "学堂详情");
                        startActivity(intent2);
                        break;
                    default:
                        Intent intent1 = new Intent(FzSchoolActivity.this, WebViewHomeActivity.class);
                        intent1.putExtra("url", mFzSchoolList.get(position).getUrl() + "");
                        intent1.putExtra("title", "学堂详情");
                        startActivity(intent1);
                        break;
                }
            }
        });
    }

    @OnClick({R.id.common_back, R.id.common_right_text,
            R.id.common_right_image, R.id.common_cancle,
            R.id.common_right_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;

            case R.id.common_right_image://搜索
                searchLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                titleLl.setVisibility(View.GONE);
                break;
            case R.id.common_cancle://取消
                searchLl.setVisibility(View.GONE);
                titleLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                break;
            case R.id.common_right_search://搜索按钮
                if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())) {
                    getAppFzSchoolData(mCateList.get(0).getId(), edtSeach.getText().toString().trim());
                } else {
                    MyToast("请输入搜索内容!");
                    return;
                }
                break;
        }
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getAppFzSchoolData(mCateList.get(0).getId(), "");
            }
        }, 2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getAppFzSchoolData(mCateList.get(0).getId(), "");
            }
        }, 2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
